﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.SqlServer;
using Microsoft.AspNet.SignalR;
using System.Windows.Forms;
using Microsoft.AspNet.SignalR.Hubs;
using System.Web.Services;
using System.Collections;

namespace SignalRChat
{
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        public void updateUnreadMessages()
        {
            var User = Membership.GetUser();
            if (User != null)
            {
                try
                {
                    Clients.Caller.updateUnreadMessages(loadAmountOfUnreadMessages());
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }

            }

            //foreach (Conversation c in loadSenders("jens"))
            //{
            //    MessageBox.Show("conversationId: "+c.conversationId.ToString()+ "\n last message time: "+c.lastTimeMessage);
            //}
            //MessageBox.Show(loadAmountOfUnreadMessages("jens").ToString());
        }

        public Boolean loggedIn()
        {
            var User = Membership.GetUser();
            if (User != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public string getUserId()
        {
            DateiaftenDataContext db = new DateiaftenDataContext();
            string userName = Membership.GetUser().UserName;
            var id = db.aspnet_Users.SingleOrDefault(x => x.UserName == userName);
            return id.UserId.ToString();
        }

        //public IEnumerable getSendersTest()
        //{
        //    string Username = Membership.GetUser().UserName;
        //    DateiaftenDataContext db = new DateiaftenDataContext();
        //    var listOfConvesations = (from c in db.Conversations
        //                              where c.Datenight.Username == Username || c.userName == Username
        //                              select new
        //                              {
        //                                  conversationId = c.conversationId,
        //                                  username = getUsername(c.Datenight.Username, c.userName),
        //                                  timeOfLastMessage = c.lastTimeMessage,
        //                                  amountOfUnreadMessage = (from m in c.Messages
        //                                                           where m.conversationId == c.conversationId
        //                                                           where m.isRead == false
        //                                                           select m).Count()
        //                              }).OrderByDescending(a => (a.amountOfUnreadMessage <= 0)).ThenByDescending(d => d.timeOfLastMessage);

        //    return listOfConvesations;
        //}

        public IEnumerable getSenders()
        {
            string Username = Membership.GetUser().UserName;
            DateiaftenDataContext db = new DateiaftenDataContext();
            var listOfConvesations = (from c in db.Conversations
                                      where c.Datenight.Username == Username || c.userName == Username
                                      select new
                                      {
                                          conversationId = c.conversationId,
                                          username = getUsername(c.Datenight.Username, c.userName),
                                          timeOfLastMessage = c.lastTimeMessage,
                                          lastMessage = c.Messages.OrderByDescending(m => m.timeOfMessage).First().Text,
                                          lastMessageUsername = c.Messages.OrderByDescending(m => m.timeOfMessage).First().userName,
                                          amountOfUnreadMessage = (from m in c.Messages
                                                                   where m.conversationId == c.conversationId
                                                                   where m.isRead == false
                                                                   where m.userName != Username
                                                                   select m).Count()
                                      }).OrderByDescending(a => (a.amountOfUnreadMessage > 0)).ThenByDescending(d => d.timeOfLastMessage);
            return listOfConvesations;
        }

        public IEnumerable getMessages(int conversationId)
        {
            MessageBox.Show("server hej 1");
            MessageBox.Show(conversationId.ToString());
            string Username = Membership.GetUser().UserName;
            MessageBox.Show("server hej 2");
            DateiaftenDataContext db = new DateiaftenDataContext();
            MessageBox.Show("server hej 3");
            Conversation conversation = null;

            try
            {
                conversation = db.Conversations.SingleOrDefault(x => x.conversationId == conversationId);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            MessageBox.Show("server hej 4");
            if (conversation.userName.ToLower() == Username.ToLower() || conversation.Datenight.Username.ToLower() == Username.ToLower())
            {
                MessageBox.Show("server hej 5");
                var listOfMessages = from m in db.Messages
                                     where m.conversationId == conversationId
                                     select new
                                     {
                                         messageId = m.MessageID,
                                         sentByUser = m.userName,
                                         messageSent = m.Text,
                                         timeOfMessageSent = m.timeOfMessage

                                     };
                MessageBox.Show("server hej 6");
                return listOfMessages;
            }
            else
            {
                MessageBox.Show("error");
                throw new Exception("Der skete en fejl. Du kan ikke hente data fra en samtale du ikke er med i.");
            }
            
            
        }

        public void updateMessages(int conversationId)
        {
            string Username = Membership.GetUser().UserName;
            DateiaftenDataContext db = new DateiaftenDataContext();
            var listOfMessages = from m in db.Messages
                                 where m.conversationId == conversationId
                                 where m.userName != Username
                                 select m;
            listOfMessages.ToList().ForEach(m => m.isRead = true);
            db.SubmitChanges();
        }

        public string getUsername(string dateNightUsername, string conversationUsername)
        {
            string Username = Membership.GetUser().UserName;
            if (dateNightUsername.ToLower().Equals(Username.ToLower()))
            {
                return conversationUsername;
            }
            else
            {
                return dateNightUsername;
            }
        }

        public IEnumerable getOtherUserByConversation(int conversationId)
        {
            string Username = Membership.GetUser().UserName;
            DateiaftenDataContext db = new DateiaftenDataContext();

            var conversation = from c in db.Conversations
                               where c.conversationId == conversationId
                               from u in db.aspnet_Users
                               where u.UserName != Username
							   where u.UserName == c.userName || u.UserName == c.Datenight.Username
                               select new
                               {
                                   username = u.UserName,
                                   age = returnAge(u.Age),
                                   city = u.City.Cityname,
                               };
            return conversation;
 
        }

        private int returnAge(DateTime? datetime)
        {
            DateTime bday = datetime.Value;
            DateTime today = DateTime.Today;
            int age = today.Year - bday.Year;
            if (bday > today.AddYears(-age)) age--;
            return age;
        }

        protected int loadAmountOfUnreadMessages()
        {
            string Username = Membership.GetUser().UserName;
            DateiaftenDataContext db = new DateiaftenDataContext();
            var ListOfBeskeder = from m in db.Messages
                                 from c in db.Conversations
                                 where c.aspnet_User.UserName == Username || c.Datenight.aspnet_User.UserName == Username
                                 where m.conversationId == c.conversationId
                                 where m.isRead == false
                                 where m.userName != Username
                                 select new { m.MessageID };


            return ListOfBeskeder.ToList().Count();
        }

        public void newMessage(int conversationId)
        {
            string Username = Membership.GetUser().UserName;
            DateiaftenDataContext db = new DateiaftenDataContext();

            Conversation conversation = db.Conversations.SingleOrDefault(x => x.conversationId == conversationId);
            if (conversation.userName == Username || conversation.Datenight.Username == Username)
            {
            }
            else
            {
            }

        }

    }
}